package com.sayimo.maker.commons.ali.pay;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.GeneratorUtils;

public class ALiTransfer {
	private static Log logger = LogFactory.getLog(ALiTransfer.class);
	/**
	 * 
	 * @MethodName aliTransfer
	 * @Description 支付宝转账
	 * @author wangyang
	 * @date 2017年2月23日 上午10:39:22
	 * @param _paramMap
	 * <pre>
	 * 	payee_account 收款方账户
	 *  payPrice 转账金额
	 *  payee_real_name  收款方真实姓名(如果本参数不为空，则会校验该账户在支付宝登记的实名是否与收款方真实姓名一致。)
	 *  remark 转账备注（支持200个英文/100个汉字）。 当付款方为企业账户，且转账金额达到（大于等于）50000元，remark不能为空。收款方可见，会展示在收款用户的账单中。
	 *  	
	 * @return Map
	 * @throws AlipayApiException 
	 */
	@SuppressWarnings({ "rawtypes"})
	public static Map aliTransfer(Map _paramMap) throws ServiceException, AlipayApiException {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//业务参数
        String payee_account= (String) _paramMap.get("payee_account");
        String amount=  String.valueOf(_paramMap.get("payPrice"));
        String payee_real_name = (String) _paramMap.get("payee_real_name");
        String remark = String.valueOf(_paramMap.get("remark"));
        
		//生成商户转账唯一订单号
		String out_biz_no=GeneratorUtils.generatorOrdersNo("004");
		
		AlipayClient alipayClient = new DefaultAlipayClient(
				"https://openapi.alipay.com/gateway.do",
				AlipayUtil.ALIPAY_APPID, AlipayUtil.APP_PRIVATE_KEY, "json",
				AlipayConstants.CHARSET_UTF8, AlipayUtil.ALIPAY_PUBLIC_KEY,
				"RSA2");
		
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("out_biz_no", out_biz_no); // 商户转账唯一订单号
		paramMap.put("payee_type", "ALIPAY_LOGONID"); // 收款方账户类型:ALIPAY_USERID：支付宝账号对应的支付宝唯一用户号,以2088开头的16位纯数字组成;ALIPAY_LOGONID：支付宝登录号，支持邮箱和手机号格式。
		paramMap.put("payee_account", payee_account); // 收款方账户
		paramMap.put("amount", amount); // 转账金额
		paramMap.put("payee_real_name", payee_real_name); // 收款方真实姓名(如果本参数不为空，则会校验该账户在支付宝登记的实名是否与收款方真实姓名一致。)
		paramMap.put("remark", remark);  //转账备注
		request.setBizContent(JSON.toJSONString(paramMap));
		
		AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
		logger.info(response.getCode());
		logger.info(response.getSubCode());
		logger.info(response.getSubMsg());
		if(response.isSuccess()){
			if ("10000".equals(response.getCode())) {
				logger.info("调用成功");
			    resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			    resultMap.put(Constant.DATA, paramMap);
			}
		} else {
			logger.info("调用失败");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_TRANSFER_FAIL);
		}
       
		return resultMap;
	}
	
	/**
	 * 
	 * @MethodName validAliTransfer
	 * @Description 查询转账是否支付成功
	 * 
	 * @author wangyang
	 * @date 2017年2月23日 上午15:36:22
	 * @param 
	 * @return Map
	 * @throws AlipayApiException 
	 */
	public static Map validAliTransfer(String out_biz_no) throws AlipayApiException{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		AlipayClient alipayClient = new DefaultAlipayClient(
				"https://openapi.alipay.com/gateway.do",
				AlipayUtil.ALIPAY_APPID, AlipayUtil.APP_PRIVATE_KEY, "json",
				AlipayConstants.CHARSET_UTF8, AlipayUtil.ALIPAY_PUBLIC_KEY, "RSA2");

		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		 // 只需要传入业务参数
        Map<String, Object> param = new HashMap<>();
        param.put("out_biz_no", out_biz_no); // 商户转账唯一订单号
        request.setBizContent(JSON.toJSONString(param));
		
		AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("status",response.getStatus());  //转账单据状态:SUCCESS:成功,INIT:等待处理,DEALING:处理中,REFUND:退票,FAIL:失败,UNKNOWN:状态未知。 
		map.put("code",response.getCode());  //网关返回码
		if(response.isSuccess()){
			if ("10000".equals(response.getCode())) {
				if("SUCCESS".equals(response.getStatus())){
					map.put("order_fee",response.getOrderFee());  //预计收费金额（元）
					map.put("pay_date",response.getPayDate());  //支付时间,转账失败不返回
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, map);
				}
			}
		} else {
			if("FAIL".equals(response.getStatus()) || "REFUND".equals(response.getStatus())){
				map.put("fail_reason",response.getFailReason());  //查询到的订单状态为FAIL失败或REFUND退票时，返回具体的原因。
			}
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.DATA, map);
		}
		return resultMap;	
	}
}
